package org.belkodevelop.announcement.service;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.belkodevelop.announcement.dao.AnnouncementDAO;
import org.belkodevelop.announcement.domain.Announcement;
import org.belkodevelop.announcement.exception.AnnouncementNotFoundException;
import org.belkodevelop.realty.service.RealtyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AnnouncementService {

    private final Log log = LogFactory.getLog(getClass()); 
    
    @Autowired
    private AnnouncementDAO announcementDAO;
    
    @Autowired
    private RealtyService realtyService;
    
    @Transactional
    public boolean removeAnnouncement(long id, long userId) {
        Announcement announcement = announcementDAO.getAnnouncement(id);
        if (announcement != null && announcement.getOwner().getId() == userId) {
            announcementDAO.removeAnnouncement(id);
            realtyService.removeRealty(announcement.getRealty().getId());
            return true;
        }
        return false;
    }

    @Transactional(readOnly=true)
    public Announcement getAnnouncement(long id) throws AnnouncementNotFoundException {
        Announcement announcement = announcementDAO.getAnnouncement(id);
        if (announcement == null) {
            throw new AnnouncementNotFoundException();
        }
        return announcement;
    }

    @Transactional
    public void addAnnouncement(Announcement announcement) {
        realtyService.addRealty(announcement.getRealty());
        announcementDAO.saveAnnouncement(announcement);
    }

    @Transactional(readOnly=true)
    public List<Announcement> getAnnouncementsByUser(long id) {
        return announcementDAO.getAnnouncementsByUser(id);
    }
    
    @Transactional(readOnly=true)
    public List<Announcement> findAnnouncement(FindRequest findRequest) {
    
        return announcementDAO.find(findRequest.getCompositeAdress(), findRequest.getType(),
                findRequest.getPriceFrom(), findRequest.getPriceTo(), findRequest.getOperationEnum());
        
    }

    @Transactional(readOnly=true)
    public Float getMaxPriceForRent() {
        return announcementDAO.getMaxPriceForRent();
    }

    @Transactional(readOnly=true)
    public Float getMaxPriceForSale() {
        return announcementDAO.getMaxPriceForSale();
    }

    @Transactional
    public void incrementRating(long id) {
        announcementDAO.incrementRatingById(id);
    }

    @Transactional
    public List<Announcement> getPremiumAnnouncements() {
        return announcementDAO.getPremiunAnnouncements();
    }

}
